import { HttpService, Injectable } from '@nestjs/common';
import { PluginNacosConfig } from './plugin-nacos-config';
import {
  PluginNacosDto, PluginNacosServiceDto, PluginNacosServiceInstanceDto,
} from './plugin-nacos.dto';

import * as qs from 'qs';


@Injectable()
export class PluginNacosService {

  constructor(private httpService: HttpService) {
  }

  /**
   * /nacos/v1/ns/service/list?pageNo=0&pageSize=10&groupName=uat&namespaceId=uat
   *
   * @param pluginNacosDto
   * @param pluginEurekaConfig
   */
  async list(pluginNacosDto: PluginNacosDto, pluginEurekaConfig: PluginNacosConfig) {

    const pluginNacosServiceList: PluginNacosServiceDto[] = [];


    const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/service/list?pageNo=${pluginNacosDto.pageNo}&pageSize=${pluginNacosDto.pageSize}&groupName=${pluginEurekaConfig.nacosGroupName}&namespaceId=${pluginEurekaConfig.nacosNamespaceId}`;
    await this.httpService.get(url, {
      headers: {},
    }).toPromise().then(async value => {
      for (let i = 0; i < value.data.doms.length; i++) {
        const pluginNacosService: PluginNacosServiceDto = {};
        const serviceName = value.data.doms[i];
        pluginNacosService.name = serviceName;
        const serviceInstanceListUrl = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/catalog/instances?serviceName=${serviceName}&clusterName=DEFAULT&groupName=${pluginEurekaConfig.nacosGroupName}&namespaceId=${pluginEurekaConfig.nacosNamespaceId}&pageNo=1&pageSize=10000`;
        const a = await this.httpService.get(serviceInstanceListUrl).toPromise().then(data => data.data);
        pluginNacosService.list = a.list as PluginNacosServiceInstanceDto[];
        pluginNacosServiceList.push(pluginNacosService);
      }
      return pluginNacosServiceList;
    }).catch(reason => {
      console.log(reason);
      return pluginNacosServiceList;
    });

    return pluginNacosServiceList;
  }

  /**
   * 服务列表
   *
   * @param dto
   * @param pluginEurekaConfig
   */
  async serviceList(dto: PluginNacosDto, pluginEurekaConfig: PluginNacosConfig) {
    const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/service/list`;
    const result = await this.httpService.get(url, {
      params: {
        pageNo: 0,
        pageSize: 10000,
        groupName: pluginEurekaConfig.nacosGroupName,
        namespaceId: pluginEurekaConfig.nacosNamespaceId,
      },
    }).toPromise()
      .then(value => value.data).catch(reason => {
        console.log(reason);
      });
    console.log('Nacos serviceList', result);
    return result;
  }


  /**
   * 实例 列表
   * @param dto
   * @param pluginEurekaConfig
   * @description 由于 /nacos/v1/ns/instance/list 获取不了已下线列表，所有调用了页面的接口 /nacos/v1/ns/catalog/instances
   */
  async instanceList(dto: PluginNacosServiceInstanceDto, pluginEurekaConfig: PluginNacosConfig) {
    // const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/instance/list`;
    const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/catalog/instances`;
    const result = await this.httpService.get(url, {
      params: {
        pageNo: 1,
        pageSize: 10000,
        clusterName: 'DEFAULT',
        serviceName: dto.serviceName,
        groupName: pluginEurekaConfig.nacosGroupName,
        namespaceId: pluginEurekaConfig.nacosNamespaceId,
      },
    }).toPromise()
      .then(value => value?.data?.list).catch(reason => {
        console.log(reason);
      });
    console.log('Nacos instanceList', result);
    return result;
  }

  async instanceInfo(dto: PluginNacosServiceInstanceDto, pluginEurekaConfig: PluginNacosConfig) {
    const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/instance`;
    const result = await this.httpService.get(url, {
      params: {
        serviceName: dto.serviceName,
        ip: dto.ip,
        port: dto.port,
        enabled: dto.enabled,
        groupName: pluginEurekaConfig.nacosGroupName,
        namespaceId: pluginEurekaConfig.nacosNamespaceId,
      },
    }).toPromise()
      .then(value => value.data).catch(reason => {
        console.log(reason);
      });
    console.log('Nacos instanceInfo', result);
    return result;
  }

  /**
   * 修改实例上下线
   * @param dto
   * @param pluginEurekaConfig
   * @return ok
   */
  async instanceChangeStatus(dto: PluginNacosServiceInstanceDto, pluginEurekaConfig: PluginNacosConfig) {
    const url = `${pluginEurekaConfig.nacosUrl}/nacos/v1/ns/instance`;
    const result = await this.httpService.put(url, qs.stringify({
        serviceName: dto.serviceName,
        ip: dto.ip,
        port: dto.port,
        enabled: dto.enabled,
        groupName: pluginEurekaConfig.nacosGroupName,
        namespaceId: pluginEurekaConfig.nacosNamespaceId,
      }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).toPromise()
      .then(value => value.data).catch(reason => {
        console.log(reason);
      });
    console.log('Nacos changeStatus', result);
    return result;
  }

}